﻿
using EmperialApps.WeatherSpark.Data;
using System;
using System.Timers;

namespace EmperialApps.WeatherSpark.Service.Internal {

    /// <summary>Represents a server timer that runs at regular intervals.</summary>
    internal sealed class SystemTimer : ITimer, IDisposable {

        /// <summary>Initializes a new instance of the <see cref="SystemTimer"/> class.</summary>
        public SystemTimer( ) {
            this._timer = new Timer( );
            this._timer.Elapsed += this.OnTimerElapsed;
        }

        /// <inheritdoc/>
        public event EventHandler Tick;

        /// <inheritdoc/>
        public void Start( TimeSpan interval ) {
            this._timer.Interval = interval.TotalMilliseconds;
            this._timer.Enabled = true;
        }

        /// <inheritdoc/>
        public void Stop( ) {
            this._timer.Enabled = false;
        }

        /// <inheritdoc/>
        public void Dispose( ) {
            this._timer.Dispose( );
        }

        #region Private Members

        private readonly Timer _timer;

        private void OnTimerElapsed( object sender, ElapsedEventArgs e ) {
            var handler = this.Tick;
            if( handler != null )
                handler( this, EventArgs.Empty );
        }

        #endregion
    }

}
